package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.dto.AddressBookDto;
import com.sky.entity.AddressBook;
import com.sky.mapper.AddressBookMapper;
import com.sky.service.IAddressBookService;
import com.sky.vo.AddressBookVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional
public class AddressBookServiceImpl implements IAddressBookService {
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Override
    public void save(AddressBookDto addressBookDto) {
        Long userId= addressBookDto.getUserId();
        //先去数据业务逻辑进行查询，如果该用户并没有设置地址，则该地址为第一个地址id 则设置成默认地址
        int num =addressBookMapper.isEmptyByUserId(userId);
        AddressBook addressBook=new AddressBook();
        BeanUtils.copyProperties(addressBookDto,addressBook);
        if(num==0){
            addressBook.setIsDefault(1);
            addressBookMapper.insert(addressBook);
        }else {
            addressBook.setIsDefault(0);
            addressBookMapper.insert(addressBook);
        }
    }

    @Override
    public List<AddressBookVo> list(Long userId) {
       List<AddressBook> addressBookList=addressBookMapper.list(userId);
      return addressBookList.stream().map((item)->{
           AddressBookVo addressBookVo= new AddressBookVo();
           BeanUtils.copyProperties(item,addressBookVo);
           return addressBookVo;
       }).collect(Collectors.toList());
    }

    @Override
    public AddressBook getDefault() {
        Long userId= BaseContext.getCurrentId();
        return addressBookMapper.getDefault(userId);
    }

    @Override
    public void modifyDefault(Long id) {
        //先得到原有默认地址对应的实体对象属性
       AddressBook addressBook=addressBookMapper.getDefault(BaseContext.getCurrentId());
       //更改
        addressBook.setIsDefault(0);
        //修改,原来的属性值为0
        addressBookMapper.modifyDefault(addressBook.getId(),addressBook.getIsDefault());
        //在将需要设置默认的地址，进行修改
        addressBookMapper.modifyDefault(id,1);
    }

    @Override
    public AddressBook getById(Long id) {
        return addressBookMapper.getById(id);
    }

    @Override
    public void deleteById(Long id) {
        addressBookMapper.deleteById(id);
    }

    @Override
    public void modifyById(AddressBookDto addressBookDto) {
        AddressBook addressBook=new AddressBook();
        BeanUtils.copyProperties(addressBookDto,addressBook);
        addressBookMapper.modifyById(addressBook);
    }
}
